package com.hmall.item.interceptor;

import com.hmall.item.utils.UserHolder;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取请求头
        String authorization = request.getHeader("authorization");
        if (StringUtils.isBlank(authorization)) {
            // 无用户消息,没登录
            response.setStatus(403);
            return false;
        }
        // 2.用户id
        Long userId = Long.parseLong(authorization);
        // 3.存入ThreadLocal
        UserHolder.setUser(userId);
        // 4.放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清空线程ThreadLocal
        UserHolder.removeUser();
    }
}
